#include "get_notice_command.h"
#include "service/backend_service.h"
#include "command_executor.h"
#include <QDebug>
#include <QUrl>
#include <QUrlQuery>
#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonArray>

GetNoticeCommand::GetNoticeCommand(QObject *parent)
    : BaseCommand(parent)
{
}

GetNoticeCommand::~GetNoticeCommand()
{
}

void GetNoticeCommand::setNetworkAccessManager(QNetworkAccessManager *networkManager)
{
    // 如果之前已经设置了 networkManager，先断开旧的连接
    if (m_networkManager) {
        disconnect(m_networkManager, &QNetworkAccessManager::finished,
                   this, &GetNoticeCommand::handleGetNoticeResponse);
    }
    
    BaseCommand::setNetworkAccessManager(networkManager);
    
    // 连接网络请求完成信号
    if (m_networkManager) {
        connect(m_networkManager, &QNetworkAccessManager::finished,
                this, &GetNoticeCommand::handleGetNoticeResponse);
    }
}

bool GetNoticeCommand::execute(int readStatus, int type, int currpage, int rowcount)
{
    if (!isValid()) {
        qDebug() << "GetNoticeCommand: BackendService 或 QNetworkAccessManager 未设置";
        emit getNoticeCompleted(-1, "BackendService 或 QNetworkAccessManager 未设置", QVariantList());
        return false;
    }
    
    qDebug() << "GetNoticeCommand: 开始获取通知消息";
    qDebug() << "参数 - readStatus:" << readStatus << "type:" << type 
             << "currpage:" << currpage << "rowcount:" << rowcount;
    
    // 获取 accessToken
    QString accessToken = CommandExecutor::getAccessToken();
    if (accessToken.isEmpty()) {
        qDebug() << "GetNoticeCommand: 没有可用的accessToken";
        emit getNoticeCompleted(-1, "没有可用的accessToken", QVariantList());
        return false;
    }
    
    // 获取 baseUrl
    QString baseUrl = getBaseUrl();
    
    // 构建请求URL
    QString url = buildRequestUrl(baseUrl);
    QString queryParams = buildQueryParams(readStatus, type, currpage, rowcount);
    if (!queryParams.isEmpty()) {
        url += "?" + queryParams;
    }
    
    qDebug() << "GetNoticeCommand: 发送获取通知消息请求到:" << url;
    
    // 创建网络请求
    QNetworkRequest request = createRequest(url, "GET", "GetNoticeCommand/1.0");
    
    // 添加token到请求头
    addTokenToRequest(request, accessToken);
    
    // 发送GET请求
    QNetworkReply *reply = m_networkManager->get(request);
    if (!reply) {
        qDebug() << "GetNoticeCommand: 创建网络请求失败";
        emit getNoticeCompleted(-1, "创建网络请求失败", QVariantList());
        return false;
    }
    
    // 设置请求类型属性
    reply->setProperty("requestType", "getNotice");
    
    qDebug() << "GetNoticeCommand: 已发送获取通知消息请求";
    
    return true;
}

void GetNoticeCommand::handleGetNoticeResponse(QNetworkReply *reply)
{
    // 检查对象是否仍然有效
    if (!isValid()) {
        qDebug() << "GetNoticeCommand: 对象已被销毁，忽略响应";
        if (reply) {
            reply->deleteLater();
        }
        return;
    }
    
    if (!reply) {
        qDebug() << "GetNoticeCommand: 获取通知响应为空";
        if (isValid()) {
            emit getNoticeCompleted(-1, "获取通知响应为空", QVariantList());
        }
        return;
    }
    
    QString requestType = reply->property("requestType").toString();
    if (requestType != "getNotice") {
        // 不是获取通知请求，忽略
        reply->deleteLater();
        return;
    }
    
    // 检查网络错误
    if (reply->error() != QNetworkReply::NoError) {
        int errorCode = reply->error();
        QString errorString = reply->errorString();
        qDebug() << "GetNoticeCommand: 获取通知网络请求错误:" << errorString;
        if (isValid()) {
            emit getNoticeCompleted(errorCode, "网络错误: " + errorString, QVariantList());
        }
        reply->deleteLater();
        return;
    }
    
    // 读取响应数据
    QByteArray responseData = reply->readAll();
    qDebug() << "GetNoticeCommand: 获取通知响应数据长度:" << responseData.size() << "字节";
    
    // 解析JSON响应
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(responseData, &parseError);
    
    // 再次检查对象是否仍然有效
    if (!isValid()) {
        qDebug() << "GetNoticeCommand: 对象已被销毁，忽略响应解析";
        reply->deleteLater();
        return;
    }
    
    if (parseError.error != QJsonParseError::NoError) {
        qDebug() << "GetNoticeCommand: 获取通知JSON解析错误:" << parseError.errorString();
        if (isValid()) {
            emit getNoticeCompleted(-1, "JSON解析错误: " + parseError.errorString(), QVariantList());
        }
        reply->deleteLater();
        return;
    }
    
    if (!doc.isObject()) {
        qDebug() << "GetNoticeCommand: 获取通知响应数据不是有效的JSON对象";
        if (isValid()) {
            emit getNoticeCompleted(-1, "响应不是有效的JSON对象", QVariantList());
        }
        reply->deleteLater();
        return;
    }
    
    QJsonObject response = doc.object();
    parseGetNoticeResponse(response);
    
    reply->deleteLater();
}

void GetNoticeCommand::parseGetNoticeResponse(const QJsonObject &response)
{
    // 检查对象是否仍然有效
    if (!isValid()) {
        qDebug() << "GetNoticeCommand: 对象已被销毁，忽略响应解析";
        return;
    }
    
    qDebug() << "GetNoticeCommand: 解析获取通知消息响应";
    
    // 检查响应状态
    int resultCode = 0;
    QString message = "成功";
    QVariantList notices;
    
    // 检查是否有错误信息
    if (response.contains("error")) {
        resultCode = -1;
        message = response["error"].toString();
        qDebug() << "GetNoticeCommand: 服务器返回错误:" << message;
    } else if (response.contains("code")) {
        resultCode = response["code"].toInt();
        if (resultCode != 0) {
            message = response.contains("message") ? response["message"].toString() : "未知错误";
            qDebug() << "GetNoticeCommand: 服务器返回错误代码:" << resultCode << "消息:" << message;
        }
    }
    
    // 解析通知列表数据
    if (resultCode == 0) {
        if (response.contains("data")) {
            QJsonValue dataValue = response["data"];
            if (dataValue.isObject()) {
                QJsonObject dataObj = dataValue.toObject();
                qDebug() << "GetNoticeCommand: data字段是对象，键列表:" << dataObj.keys();
                
                // 检查是否有datas数组
                if (dataObj.contains("datas") && dataObj["datas"].isArray()) {
                    QJsonArray datasArray = dataObj["datas"].toArray();
                    qDebug() << "GetNoticeCommand: 找到datas数组，数量:" << datasArray.size();
                    
                    for (const QJsonValue &value : datasArray) {
                        if (value.isObject()) {
                            QJsonObject noticeObj = value.toObject();
                            QVariantMap noticeMap;
                            
                            // 将JSON对象转换为QVariantMap
                            for (auto it = noticeObj.begin(); it != noticeObj.end(); ++it) {
                                noticeMap[it.key()] = it.value().toVariant();
                            }
                            
                            notices.append(noticeMap);
                        }
                    }
                    qDebug() << "GetNoticeCommand: 解析到" << notices.size() << "条通知";
                } else {
                    qDebug() << "GetNoticeCommand: data对象中没有datas数组";
                }
            } else {
                qDebug() << "GetNoticeCommand: data字段不是对象";
            }
        } else {
            qDebug() << "GetNoticeCommand: 响应中没有data字段";
        }
    }
    
    // 最后一次检查对象是否仍然有效
    if (!isValid()) {
        qDebug() << "GetNoticeCommand: 对象已被销毁，无法发送完成信号";
        return;
    }
    
    // 发送完成信号
    emit getNoticeCompleted(resultCode, message, notices);
}

QString GetNoticeCommand::buildQueryParams(int readStatus, int type, int currpage, int rowcount)
{
    QUrlQuery query;
    
    // 只有当readStatus不为-1时才添加readStatus参数
    if (readStatus != -1) {
        query.addQueryItem("readStatus", QString::number(readStatus));
    }
    
    // 移除type参数，因为API不需要这个参数
    
    // 添加分页参数
    query.addQueryItem("_currpage", QString::number(currpage));
    query.addQueryItem("_rowcount", QString::number(rowcount));
    
    return query.toString();
}

QString GetNoticeCommand::buildRequestUrl(const QString &baseUrl)
{
    return baseUrl + "/message/api/message/notice";
}

